import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

interface tagType {
  title: string
  path: string
}

const useTagsViewStore = defineStore(
  'tagsView',
  () => {
    // 声明数据  数据保存tags页签中的数据 数组
    // [{title:xxxx,path:xxxx},{},...]
    const tagsList = ref([] as tagType[])
    const active = ref('')

    // 新增
    const add = (item: tagType) => {
      const index = tagsList.value.findIndex((v) => v.path === item.path)
      if (index !== -1) return

      tagsList.value.push(item)
    }

    // 删除
    const remove = (path: string) => {
      if (tagsList.value.length === 1) {
        return ElMessage.warning('至少保留一个页签')
      }

      const index = tagsList.value.findIndex((v) => v.path === path)
      tagsList.value.splice(index, 1)

      if (path === active.value) {
        active.value = tagsList.value[index - 1].path
      }
    }

    return { tagsList, active, add, remove }
  },
  {
    persist: true,
  },
)

export default useTagsViewStore
